;(function () {
  //zero 0
  function toDou(num) {
    return num < 10 ? '0' + num : '' + num;
  }
  //sort json
  function compareAsc(propertyName) {
    return function(object1, object2) {
        var value1 = object1[propertyName];
        var value2 = object2[propertyName];
        if(value2 < value1) {
            return 1;
        } else if(value2 > value1) {
            return -1;
        } else {
            return 0;
        }
    }
  }
  //day
  function diffDay (day1, day2) {
    //day1起始时间
    //day2结束时间
    var day1s = day1.split('-')
    var day2s = day2.split('-')
    var oEndDate = new Date();
    oEndDate.setFullYear(day2s[0],Number(day2s[1])-1,day2s[2]);
    oEndDate.setHours(0,0,0,0);
    var oBeginDate = new Date();
    oBeginDate.setFullYear(day1s[0],Number(day1s[1])-1,day1s[2]);
    oBeginDate.setHours(0,0,0,0);
    var iS = parseInt((oEndDate.getTime()-oBeginDate.getTime())/1000);

    var iD = parseInt(iS / 86400);
    iS %= 86400;
    var iH = parseInt(iS / 3600);
    iS %= 3600;
    var iM = parseInt(iS / 60);
    iS %= 60;

    return iD
  }

  new Vue({
    el: '#unitYuce',
    data: {
      unitType: [],
      projectData: [],
      buildingData: [],
      floorData: [],
      saveId: {projectId: '', buildingId: '', floorId: '', formatsId: ''},
      names: {projectName: '', buildingName: ''},
      listData: [],
      colorData: [],
      position: {left: 0, top: 0},
      showPositon: false,
      typeNumber: '',
      tempJson: {},
      temoInfoJson: {},
      ycRent: '',
      ycPrent: '',
      addYuceFlag: false,
      clickName: '',
      timeType: [{name: '元/m²/天', code: 'D'},{name: '元/m²/月', code: 'M'}],
      timeTypeAct: 'D',
      exclFlag: false,
      exclFlagShow: false,
      exclParams: {flag: false, data: [], postFlag: '0'},  //0验证  1错误  2通过
      quanxianSet: JSON.parse(window.localStorage.getItem('permissions')),
      beginDateYc:'',
      endDateYc:'',
    },
    computed: {
      //往后推俩年
      setYearNumber () {
        var arr = [];
        var year = new Date().getFullYear();
        for (var i = 0; i < 3; i++) {
          arr.push(year+i)
        }
        return arr
      },
      //推算月份
      setMonthNumber () {
        var arr = [];
        var year = new Date().getMonth();
        var count = 12;
        for (var j = 0; j < 2; j++) {
          for (var i = 0; i < 12; i++) {
            arr.push(i+1)
          }
        }
        for (var i = 0; i < (count-year); i++) {
          arr.unshift(count-i)
        }
        return arr
      },
      //设置月份宽度
      setMonthWd () {
        var total = 741;
        var result;
        result = 741/this.setMonthNumber.length;
        return {width: result+'px',lineHeight: '30px'}
      },
      //设置年份宽度
      setYearWd () {
        var arr = [];
        var total = 741;
        var result;
        result = 741/this.setMonthNumber.length;
        var year = 12 - new Date().getMonth();
        arr.push({width:(result*year)+'px',lineHeight: '35px'})
        arr.push({width:(result*12)+'px',lineHeight: '35px'})
        arr.push({width:(result*12)+'px',lineHeight: '35px'})
        return arr
      },
      //计算总天数
      totalDay () {
        var result = 0;
        var day = new Date().getFullYear() + '-' + (new Date().getMonth()+1) +'-01'
        result = diffDay(day, (new Date().getFullYear()+2) +'-12-31')
        return result
      }
    },
    filters: {
      to2 (n) {
        return Number(n).toFixed(2)
      }
    },
    methods: {
      //项目
      getProject () {
        hlhttp.get({
          url: 'user/projects',
          success: res => {
            this.projectData = res;
          }
        })
      },
      //楼宇
      getBuilding (id, name) {
        document.querySelector('.building-name').innerHTML = '请选择';
        document.querySelector('.floor-name').innerHTML = '请选择';
        this.saveId = {projectId: id, buildingId: '', floorId: '', formatsId: ''}
        this.names = {projectName: name, buildingName: ''}
        hlhttp.get({
          url: 'project/buildings',
          data: {project_id: id},
          success: res => {
            this.buildingData = res;
          }
        })
      },
      //楼层
      getFloor (id, name) {
        document.querySelector('.floor-name').innerHTML = '请选择';
        this.saveId = {projectId: this.saveId.projectId, buildingId: id, floorId: '', formatsId: ''}
        this.names = {projectName: this.names.projectName, buildingName: name}
        hlhttp.get({
          url: 'building/floors',
          data: {project_id: this.saveId.projectId, building_id: id},
          success: res => {
            this.floorData = res;
          }
        })
      },
      //业态
      getFormats () {
        hlhttp.get({
          url: 'unit/business_types',
          success: (res) => {
            res.unshift({code: '#', memo: '全部'})
            this.unitType = res;
          }
        })
      },
      //重置
      resetData () {
        this.exclParams.flag = false;
        this.saveId = {projectId: '', buildingId: '', floorId: '', formatsId: ''}
        document.querySelector('.project-name').innerHTML = '请选择';
        document.querySelector('.building-name').innerHTML = '请选择';
        document.querySelector('.floor-name').innerHTML = '请选择';
        document.querySelector('.yetai-name').innerHTML = '请选择';
      },
      //获得业态
      getType (val) {
        this.saveId.formatsId = val;
      },
      //获得楼层id
      getfloorId (id) {
        this.saveId.floorId = id;
      },
      //操作按钮
      orgeGetInfo (e, item, i, maxI, ii) {
        this.showPositon = true;
        this.typeNumber = item.typeNumber;
        this.tempJson = item;

        if (i < maxI-1) {
          if (this.tempJson.typeNumber == '1') {
            if (this.listData[ii].list[i+1].typeNumber == '2') {
              this.tempJson.maxTime = this.listData[ii].list[i+1].endDate
            }
            if (!(this.listData[ii].list[i+1].typeNumber == '2')) {
              this.tempJson.maxTime = this.tempJson.endDate
            }
          }
        }
        if (i > 0) {
          if (this.tempJson.typeNumber == '1') {
            if (this.listData[ii].list[i-1].typeNumber == '2') {
              this.tempJson.minTime = this.listData[ii].list[i-1].beginDate
            }
            if (!(this.listData[ii].list[i-1].typeNumber == '2')) {
              this.tempJson.minTime = this.tempJson.beginDate
            }
          }
        }
        this.temoInfoJson = e.target.offsetParent.parentElement.parentElement.dataset;
        setTimeout(() => {
          var boxHeight = (40-document.querySelector('.position-top').offsetHeight)/2;
          var top = (e.target.offsetParent.offsetTop+boxHeight)
          this.position = {
            left: (e.target.offsetParent.offsetLeft+item.showNumber+5)+'px',
            top: top+'px',
            zIndex: 9
          }
        }, 50);
        setTimeout(() => {
          if (this.showPositon) {
            this.showPositon = false;
            this.typeNumber = '';
            this.position = {left: 0, top:0, zIndex: '-1'}
          }
        }, 4000);

      },
      //0  查看详情
      seeDetails () {
        hlUrlUtil.goTo('contractNewDeatil', {id: this.tempJson.contractId , proId: this.saveId.projectId, version: '#', ddtab:true} , true)
      },
      //显示新增预测框框
      showYuceAdd () {
        this.addYuceFlag = true;
        this.showPositon = false;
        this.typeNumber = '';
        this.position = {left: 0, top:0, zIndex: '-1'}

        setTimeout(() => {
          this.beginDateYc = this.tempJson.beginDate
          this.endDateYc = this.tempJson.endDate
        }, 50);
      },
      //隐藏新增预测框框
      hideYuceAdd () {
        this.addYuceFlag = false;
        this.showPositon = false;
        this.typeNumber = '';
        this.position = {left: 0, top:0, zIndex: '-1'}
        this.tempJson = {}
        this.ycRent = '';
        this.ycPrent = '';
      },
      //获取点击时间名字
      getClickName (name) {
        this.clickName = name;
      },
      // 新增预测时间验证
      yuceDate () {
        var date,stamp,sortStamp;
        $('.dt-dateControl').on('click', '.day-item', (event) => {
          date = $('.setYear .select-name').text()+'-'+toDou(Number($('.setMonth .select-name').text()))+'-'+toDou(Number(event.target.innerText));
          stamp = hlDateUtil.shellDate(date)

          if (this.clickName == 'beginDateYc') {
            sortStamp = hlDateUtil.shellDate(this.tempJson.beginDate);
            this.beginDateYc = date;
            if (this.tempJson.typeNumber == '2') {
              if (stamp < sortStamp) {
                hl.toast('当前可选择的时间范围：'+this.tempJson.beginDate+'至'+this.tempJson.endDate)
                this.beginDateYc = ''
                this.endDateYc = ''
              }
            }
            if (this.tempJson.typeNumber == '1') {
              if (stamp < hlDateUtil.shellDate(this.tempJson.minTime)) {
                hl.toast('当前可选择的时间范围：'+this.tempJson.minTime+'至'+this.tempJson.maxTime)
                this.beginDateYc = ''
                this.endDateYc = ''
              }
            }
          }

          if (this.clickName == 'endDateYc') {
            sortStamp = hlDateUtil.shellDate(this.tempJson.endDate);
            this.endDateYc = date;
            if (!this.beginDateYc) {
              hl.toast('请先选择起始时间')
              this.endDateYc = ''
              return
            }
            if (stamp <= hlDateUtil.shellDate(this.beginDateYc)) {
              hl.toast('截止时间不能小于起始时间')
              this.endDateYc = ''
              return
            }
            if (this.tempJson.typeNumber == '2') {
              if (stamp > sortStamp) {
                hl.toast('当前可选择的时间范围：'+this.tempJson.beginDate+'至'+this.tempJson.endDate)
                this.endDateYc = ''
              }
            }
            if (this.tempJson.typeNumber == '1') {
              if (stamp > hlDateUtil.shellDate(this.tempJson.maxTime)) {
                hl.toast('当前可选择的时间范围：'+this.tempJson.minTime+'至'+this.tempJson.maxTime)
                this.endDateYc = ''
              }
            }
          }
          this.clickName = ''
          date = ''
        });
      },
      //2 新增预测
      addYuce () {
        if (!this.beginDateYc) {
          hl.toast('请选择起始时间')
          return
        }
        if (!this.endDateYc) {
          hl.toast('请选择截止时间')
          return
        }
        if (!this.ycRent) {
          hl.toast('请填写预测租金')
          return
        }
        if (!this.timeTypeAct) {
          hl.toast('请选择预测租金类型')
          return
        }
        if (!this.ycPrent) {
          hl.toast('请填写预测可能')
          return
        }
        hlhttp.post({
          url: 'unit/price/forecast',
          data: {
            project_id: this.temoInfoJson.projectid,
            project_name: this.temoInfoJson.projectname,
            building_id: this.temoInfoJson.buildingid,
            building_name: this.temoInfoJson.buildingname,
            floor_id: this.temoInfoJson.floorid,
            floor_name: this.temoInfoJson.floorname,
            unit_id: this.temoInfoJson.unitid,
            unit_name: this.temoInfoJson.unitname,
            begin_date: this.beginDateYc,
            end_date: this.endDateYc,
            rent_price: this.ycRent,
            rent_price_type: this.timeTypeAct,
            rent_possible_percent: this.ycPrent
          },
          success: res => {
            hl.toast('新增预测成功')
            this.searchUnit()
            this.hideYuceAdd()
          }
        })
      },
      //编辑预测
      editYuce () {
        this.addYuceFlag = true;
        setTimeout(() => {
          this.beginDateYc = this.tempJson.beginDate
          this.endDateYc = this.tempJson.endDate
          if (this.tempJson.rentPriceType == 'M') {
            $('.select-yuce span').text(this.timeType[1].name)
          }
          if (this.tempJson.rentPriceType == 'D') {
            $('.select-yuce span').text(this.timeType[0].name)
          }
        }, 50);
        this.ycRent = this.tempJson.rentPrice;
        this.ycPrent = this.tempJson.rentPossiblePercent;
        this.timeTypeAct = this.tempJson.rentPriceType
      },
      //删除预测
      delYuce () {
        hllayer.confirm('确认要删除当前租金预测?',
          () => {
            hlhttp.delete({
              url: 'unit/price/forecast?id='+this.tempJson.id,
              success: res => {
                hl.toast('删除预测成功')
                this.searchUnit()
                this.hideYuceAdd()
              }
            })
          }
        )
      },
      //更新预测
      putYuce () {
        hlhttp.put({
          url: 'unit/price/forecast',
          data: {
            id: this.tempJson.id,
            begin_date: this.beginDateYc,
            end_date: this.endDateYc,
            rent_price: this.ycRent,
            rent_price_type: this.timeTypeAct,
            rent_possible_percent: this.ycPrent
          },
          success: res => {
            hl.toast('编辑预测成功')
            this.searchUnit()
            this.hideYuceAdd()
          }
        })
      },
      //搜索单元的信息
      searchUnit () {
        if (!this.saveId.projectId) {
          hl.toast('请选择项目')
          return
        }
        if (!this.saveId.buildingId) {
          hl.toast('请选择楼宇')
          return
        }
        hlhttp.get({
          url: 'search/project/unit',
          data: {
            project_id: this.saveId.projectId,
            building_id: this.saveId.buildingId,
            floor_id: this.saveId.floorId || '#',
            business_type: this.saveId.formatsId || '#'
          },
          success: res => {
            var arr = []
            res.map(item => {
              item.list = []
              this.unitType.map(item1 => {
                if (item.businessType == item1.code) {
                  item.typeName = item1.memo
                }
              })
              arr.push(item.unitId)
            })
            this.listData = res;
            this.rentYc(arr)
          }
        })
      },
      //获取租金预测
      rentYc (ids) {
        hlhttp.get({
          url: 'unit/price/forecast',
          data: {
            unit_ids: ids.toString()
          },
          success: res => {
            this.exclParams.flag = true;
            this.colorData = res;
            this.dealWith()
          }
        })
      },
      //处理获得时间预测数据
      dealWith () {
        //0 绿色  1 黄色  2灰色
        var arr = [];
        var oEndDate = new Date();
        oEndDate.setFullYear(oEndDate.getFullYear(),oEndDate.getMonth(),1);
        oEndDate.setHours(0,0,0,0);
        var flagMoney = false, lindex = 0;
        this.colorData.map(item => {
          lindex = 0;
          item.contracts.map((item1, index9) => {
            flagMoney = false;
            if (hlDateUtil.shellDate(item1.beginDate) < oEndDate.getTime() && hlDateUtil.shellDate(item1.endDate) > oEndDate.getTime()) {
              flagMoney = true;
              item1.beginDate = oEndDate.getFullYear() +'-'+ toDou(oEndDate.getMonth()+1) + '-01';
              if (hlDateUtil.shellDate(item1.endDate) > hlDateUtil.shellDate((new Date().getFullYear()+2) +'-12-31')) {
                item1.endDate = (new Date().getFullYear()+2) +'-12-31'
              }
            }
            if (hlDateUtil.shellDate(item1.beginDate) < oEndDate.getTime() && hlDateUtil.shellDate(item1.endDate) < oEndDate.getTime()) {
              item1.beginDate = '2017-12-31';
              item1.endDate = '2017-12-30';
              item1.rentIncreseDate = ''
            }
            if (!item1.rentIncreseDate) {
              arr.push({
                beginDate: item1.beginDate,
                contractId: item1.contractId,
                endDate: item1.endDate,
                "rentIncresePercent": item1.rentIncresePercent,
                "rentIncreasePrice": item1.rentIncreasePrice,
                "rentIncreseMonth": item1.rentIncreseMonth,
                rentIncreseDay: item1.rentIncreseDay,
                rentWay: item1.rentWay,
                unitId: item1.unitId,
                sortNumber: hlDateUtil.shellDate(item1.beginDate),
                typeNumber: '0'
              })
            }
            var delIndex = 0;
            if (item1.rentIncreseDate) {
              item1.rentIncresePercent = item1.rentIncresePercent.split(',');
              item1.rentIncreasePrice = item1.rentIncreasePrice.split(',');
              item1.rentIncreseDay = item1.rentIncreseDay.split(',');
              item1.rentIncreseMonth = item1.rentIncreseMonth.split(',');
              item1.rentIncreseDate = item1.rentIncreseDate.split(',');

              item1.rentIncreseDate.map((item2, index) => {
                if (hlDateUtil.shellDate(item2) < oEndDate.getTime()) {
                  delIndex++
                }
                if (hlDateUtil.shellDate(item2) == hlDateUtil.shellDate(item1.beginDate)) {
                  delIndex++
                }
                if (hlDateUtil.shellDate(item2) > hlDateUtil.shellDate((new Date().getFullYear()+2) +'-12-31')) {
                  item1.rentIncreseDate[index] = (new Date().getFullYear()+2) +'-12-31'
                }
              })

              item1.rentIncreseDate.splice(0, delIndex)
              item1.rentIncreseMonth.splice(0, delIndex-1) //月租金
              item1.rentIncreseDay.splice(0, delIndex-1) //日租金
              item1.rentIncresePercent.splice(0, delIndex-1) //递增率
              item1.rentIncreasePrice.splice(0, delIndex-1) //租金递增价

              if (!item1.rentIncreseDate[0]) {
                arr.push({
                  beginDate: item1.beginDate,
                  contractId: item1.contractId,
                  endDate: item1.endDate,
                  "rentIncresePercent": item1.rentIncresePercent[0],
                  "rentIncreasePrice": item1.rentIncreasePrice[0],
                  "rentIncreseMonth": item1.rentIncreseMonth[0],
                  rentIncreseDay: item1.rentIncreseDay[0],
                  rentWay: item1.rentWay,
                  unitId: item1.unitId,
                  sortNumber: hlDateUtil.shellDate(item1.beginDate),
                  typeNumber: '0'
                })
              }
              item1.rentIncreseDate.map((item2, index) => {
                if (item1.rentIncreseDate[0]) {
                  if (index == 0 && hlDateUtil.shellDate(item1.rentIncreseDate[0]) < hlDateUtil.shellDate(item1.endDate)) {
                    arr.push({
                      beginDate: item1.beginDate,
                      contractId: item1.contractId,
                      endDate: hlDateUtil.formatDate(hlDateUtil.shellDate(item1.rentIncreseDate[0])-(24*60*60*1000), 'yyyy-MM-dd'),
                      "rentIncresePercent": item1.rentIncresePercent[0],
                      "rentIncreasePrice": item1.rentIncreasePrice[0],
                      "rentIncreseMonth": item1.rentIncreseMonth[0],
                      rentIncreseDay: item1.rentIncreseDay[0],
                      rentWay: item1.rentWay,
                      unitId: item1.unitId,
                      sortNumber: hlDateUtil.shellDate(item1.beginDate),
                      typeNumber: '0'
                    })
                  }
                  if (index == 0 && hlDateUtil.shellDate(item1.rentIncreseDate[0]) >= hlDateUtil.shellDate(item1.endDate)) {
                    arr.push({
                      beginDate: item1.beginDate,
                      contractId: item1.contractId,
                      endDate: hlDateUtil.formatDate(hlDateUtil.shellDate(item1.rentIncreseDate[0]), 'yyyy-MM-dd'),
                      "rentIncresePercent": item1.rentIncresePercent[0],
                      "rentIncreasePrice": item1.rentIncreasePrice[0],
                      "rentIncreseMonth": item1.rentIncreseMonth[0],
                      rentIncreseDay: item1.rentIncreseDay[0],
                      rentWay: item1.rentWay,
                      unitId: item1.unitId,
                      sortNumber: hlDateUtil.shellDate(item1.beginDate),
                      typeNumber: '0'
                    })
                  }
                  if (index > 0) {
                    arr.push({
                      beginDate: item1.rentIncreseDate[index-1],
                      contractId: item1.contractId,
                      endDate: hlDateUtil.formatDate(hlDateUtil.shellDate(item1.rentIncreseDate[index])-(24*60*60*1000), 'yyyy-MM-dd'),
                      "rentIncresePercent": item1.rentIncresePercent[index],
                      "rentIncreasePrice": item1.rentIncreasePrice[index],
                      "rentIncreseMonth": item1.rentIncreseMonth[index],
                      rentIncreseDay: item1.rentIncreseDay[index],
                      rentWay: item1.rentWay,
                      unitId: item1.unitId,
                      sortNumber: hlDateUtil.shellDate(item1.rentIncreseDate[index-1]),
                      typeNumber: '0'
                    })
                  }
                }
              })
              if (hlDateUtil.shellDate(item1.rentIncreseDate[item1.rentIncreseDate.length-1]) < hlDateUtil.shellDate(item1.endDate)) {
                arr.push({
                  beginDate: item1.rentIncreseDate[item1.rentIncreseDate.length-1],
                  contractId: item1.contractId,
                  endDate: hlDateUtil.formatDate(hlDateUtil.shellDate(item1.endDate), 'yyyy-MM-dd'),
                  "rentIncresePercent": item1.rentIncresePercent[item1.rentIncreseDate.length],
                  "rentIncreasePrice": item1.rentIncreasePrice[item1.rentIncreseDate.length],
                  "rentIncreseMonth": item1.rentIncreseMonth[item1.rentIncreseDate.length],
                  rentIncreseDay: item1.rentIncreseDay[item1.rentIncreseDate.length],
                  rentWay: item1.rentWay,
                  unitId: item1.unitId,
                  sortNumber: hlDateUtil.shellDate(item1.rentIncreseDate[item1.rentIncreseDate.length-1]),
                  typeNumber: '0'
                })
              }
            }
          })
          item.units.map(itemUnit => {
            if (hlDateUtil.shellDate(itemUnit.endDate) > hlDateUtil.shellDate((new Date().getFullYear()+2) +'-12-31') && hlDateUtil.shellDate(itemUnit.beginDate) < hlDateUtil.shellDate((new Date().getFullYear()+2) +'-12-31')) {
              itemUnit.endDate = (new Date().getFullYear()+2) +'-12-31'
            }
            if (hlDateUtil.shellDate(itemUnit.beginDate) < oEndDate.getTime() && hlDateUtil.shellDate(itemUnit.endDate) > oEndDate.getTime()) {
              itemUnit.beginDate = hlDateUtil.formatDate(oEndDate.getTime(), 'yyyy-MM-dd')
            }
            if (hlDateUtil.shellDate(itemUnit.endDate) > oEndDate.getTime()) {
              if (hlDateUtil.shellDate(itemUnit.beginDate) < oEndDate.getTime()) {
                itemUnit.beginDate = oEndDate.getFullYear() +'-'+ toDou(oEndDate.getMonth()+1) + '-01';
              }
              arr.push({
                id: itemUnit.id,
                beginDate: itemUnit.beginDate,
                endDate: itemUnit.endDate,
                rentPrice: itemUnit.rentPrice,
                rentPriceType: itemUnit.rentPriceType,
                rentPossiblePercent: itemUnit.rentPossiblePercent,
                unitId: itemUnit.unitId,
                sortNumber: hlDateUtil.shellDate(itemUnit.beginDate),
                typeNumber: '1'
              })
            }
          })
        })

        this.listData.map((item, index) => {
          arr.map(item1 => {
            if (item.unitId == item1.unitId) {
              item.list.push(item1)
            }
          })
        })
        this.listData.map((item, index) => {
          item.list = item.list.sort(compareAsc("sortNumber"))
        })

        this.listData.map((item, index) => {
          item.list.map((item1s, index1s) => {
            if (hlDateUtil.shellDate(item1s.beginDate) > hlDateUtil.shellDate((new Date().getFullYear()+2) +'-12-31')) {
              item.list.splice(index1s, 1)
              item.list.length--;
              index1s--;
            }
          })
        })

        var dateArr = this.listData,
            listArr,
            pushIndex = 0;
        for (var i = 0; i < dateArr.length; i++) {
          listArr = dateArr[i].list;
          for (var k = 0; k < listArr.length; k++) {
            if (k < listArr.length-1) {
              if (hlDateUtil.shellDate(listArr[k].endDate) < (hlDateUtil.shellDate(listArr[k+1].beginDate)-(24*60*60*1000))) {
                listArr.splice(k+1, 0, {
                  beginDate: hlDateUtil.formatDate(hlDateUtil.shellDate(listArr[k].endDate)+(24*60*60*1000), 'yyyy-MM-dd'),
                  typeNumber: '2',
                  endDate: hlDateUtil.formatDate(hlDateUtil.shellDate(listArr[k+1].beginDate)-(24*60*60*1000), 'yyyy-MM-dd'),
                  sortNumber: hlDateUtil.shellDate(listArr[k].endDate)+(24*60*60*1000)
                })
              }
            }
          }
          if (listArr.length) {
            if ((hlDateUtil.shellDate(listArr[0].beginDate)-(24*60*60*1000)) > oEndDate.getTime()) {
              listArr.unshift({
                beginDate: hlDateUtil.formatDate(oEndDate.getTime(), 'yyyy-MM-dd'),
                typeNumber: '2',
                endDate: hlDateUtil.formatDate((hlDateUtil.shellDate(listArr[0].beginDate)-(24*60*60*1000)), 'yyyy-MM-dd'),
                sortNumber: oEndDate.getTime()
              })
            }
          }
          if (listArr.length > 0) {
            if (hlDateUtil.shellDate(listArr[listArr.length-1].endDate) < hlDateUtil.shellDate((new Date().getFullYear()+2) +'-12-31')) {
              listArr.push({
                beginDate: hlDateUtil.formatDate(hlDateUtil.shellDate(listArr[listArr.length-1].endDate)+(24*60*60*1000), 'yyyy-MM-dd'),
                typeNumber: '2',
                endDate: (new Date().getFullYear()+2) +'-12-31',
                sortNumber: hlDateUtil.shellDate(listArr[listArr.length-1].endDate)+(24*60*60*1000)
              })
            }
          }
        }
        this.listData.map((item, index) => {
          if (!item.list.length) {
            item.list.push({
              beginDate: hlDateUtil.formatDate(oEndDate.getTime(), 'yyyy-MM-dd'),
              typeNumber: '2',
              endDate: (new Date().getFullYear()+2) +'-12-31',
              sortNumber: hlDateUtil.shellDate(hlDateUtil.formatDate(oEndDate.getTime(), 'yyyy-MM-dd'))
            })
          }
        })

        var count0 = 0;
        this.listData.map((item, index) => {
          count0 = 0;
          item.list.map((item1, index1) => {
            if (index1 < item.list.length-1) {
              item1.proportion = Math.ceil(diffDay(item1.beginDate, hlDateUtil.formatDate(hlDateUtil.shellDate(item1.endDate)+(24*60*60*1000), 'yyyy-MM-dd'))/this.totalDay*741)+'px'
              item1.showNumber = Math.ceil(diffDay(item1.beginDate, hlDateUtil.formatDate(hlDateUtil.shellDate(item1.endDate)+(24*60*60*1000), 'yyyy-MM-dd'))/this.totalDay*741);
              count0 += Math.ceil(diffDay(item1.beginDate, hlDateUtil.formatDate(hlDateUtil.shellDate(item1.endDate)+(24*60*60*1000), 'yyyy-MM-dd'))/this.totalDay*741)
            }
            if (index1 == item.list.length-1) {
              item1.proportion = 741-count0+'px'
              item1.showNumber = 741-count0
            }
          })
        })

      },
      //底部固定
      scrollBottom () {

        function autoMixHeight () {
          var scrollTop = $(document).scrollTop();
          var scrollHeight = $(document).height();
          var windowHeight = $(this).height();
          for (var i = 0; i < 19; i++) {
    				if(scrollTop + windowHeight == scrollHeight - i){
    					$('.footer-template').css({
    						'bottom': 20-i
    					})
    			　}
    			}
          if(scrollTop + windowHeight == scrollHeight){
            $('.footer-template').css({
              'bottom': '30px'
            })
        　}
        if(scrollTop + windowHeight < scrollHeight){
          $('.footer-template').css({
            'bottom': '10px'
          })
      　}
        }
        $(window).scroll(function(event) {
  				autoMixHeight()
  			});

      },

      //excl表格
      exclTab () {
        window.Excel = function() {
          this.data = [] // EXCEL数据
          this.checkResult = false // EXCEL规范检测结果
        }
        var keyIndex;
        Excel.prototype.check = function(formSelector, fileSelector, checkStr, suc) {
          var self = this;
          keyIndex = 0;
          document.querySelector(fileSelector).addEventListener('change', function(e) {
            var files = e.target.files;
            var fileReader = new FileReader();
            self.data = []
            // 以二进制方式打开文件
            fileReader.readAsBinaryString(files[0]);

            fileReader.onload = function(ev) {
              try {
                var result = ev.target.result,
                  workbook = XLSX.read(result, {
                    type: "binary"
                  }); // 以二进制流方式读取得到整份excel表格对象
              } catch(e) {
                return;
              }

              var fromTo = ''; //要读取EXCEL的表格范围   A1:C4
              var excelHeadStr = ''; //读取的EXCEL表头
              var headCol = ''; //表头列号
              var arr = ['A1', 'B1', 'C1', 'D1', 'E1', 'F1', 'G1', 'H1', 'I1', 'J1', 'K1', 'L1', 'M1', 'N1', 'O1', 'P1', 'Q1', 'R1', 'S1', 'T1', 'U1', 'V1', 'W1', 'X1', 'Y1', 'Z1']
              var index;

              // 遍历workbook下的Sheets对象来读取每一个上传文件的内容
              for(var sheet in workbook.Sheets) {
                if(workbook.Sheets.hasOwnProperty(sheet)) {
                  fromTo = workbook.Sheets[sheet]["!ref"]; // 获取EXCEl文件中存在数据的行号和列号
                  for(var j = 0; j < 9; j++) {
                    excelHeadStr += workbook.Sheets[sheet][arr[j]].h + ','
                  }

                  // 去除字符串末尾','
                  excelHeadStr = excelHeadStr.substring(0, excelHeadStr.length - 1)
                  if(excelHeadStr == checkStr) {
                    self.checkResult = true
                  } else {
                    hl.toast('请上传正确的模板')
                    self.checkResult = false
                  }
                  self.data = self.data.concat(XLSX.utils.sheet_to_json(workbook.Sheets[sheet]));
                  Excel.data = self.data;
                  break; //只取第一张表
                }
              }
              keyIndex++
              if (keyIndex == 1) {
                suc && suc(Excel.data)
              }
            };
          })

        }
      },
      //显示上传框框
      showExcl () {
        this.exclFlag = true;
        this.exclFlagShow = false;
      },
      //隐藏上传框框
      hideExcl () {
        this.exclFlag = false;
        this.exclFlagShow = false;
        exclName.value = '';
        this.exclParams.data = [];
        this.exclParams.postFlag = '0';
      },
      //导出表格
      extExcl () {
        if (!this.saveId.projectId) {
          hl.toast('请选择项目')
          return
        }
        if (!this.saveId.buildingId) {
          hl.toast('请选择楼宇')
          return
        }
        $.ajax({
          url: exclUrl+'resource/unit_price_forecast_excel',
          contentType:'application/x-www-form-urlencoded',
          type: 'get',
          headers: {
            token: Cookies.get("token")
          },
          data: {
            project_id: this.saveId.projectId,
            building_id: this.saveId.buildingId,
            floor_id: this.saveId.floorId || '',
            business_type: this.saveId.formatsId || ''
          },
          success: res => {
            window.open(res.excel_url)
          },
          error: res => {
            hl.toast(JSON.parse(res.responseText).msg)
          }
        })
      },
      //表格数据获取
      updateExcl () {
        $('#excel-file').trigger('click')
        new Excel().check('#excel-form', '#excel-file', '项目,楼栋,楼层,单元,开始时间,结束时间,租金单价,租金单位,出租可能', (data) => {
          var str = document.querySelector('#excel-file').value;
          exclName.value = str.substr(str.lastIndexOf('\\')+1);
          document.querySelector('#excel-file').value = '';
          this.validExcl(data)
        })
      },
      //处理excl数据，并且验证时间交错
      validExcl (data) {
        var arr = [];
        data.map(item => {
          arr.push({
            project_name: item['项目'],
            building_name: item['楼栋'],
            floor_name: item['楼层'],
            unit_name: item['单元'],
            begin_date: item['开始时间'],
            end_date: item['结束时间'],
            rent_price: item['租金单价'],
            rent_price_type: item['租金单位'],
            rent_possible_percent: item['出租可能']
          })
        })

        var bd, ed; //bd开始时间  ed结束时间
        arr.map(item => {
          if (item.begin_date.indexOf('/') > -1) {
            bd = item.begin_date.split('/');
            item.begin_date = '20'+toDou(Number(bd[2]))+'-'+toDou(Number(bd[0]))+'-'+toDou(Number(bd[1]))
          }
          if (item.end_date.indexOf('/') > -1) {
            ed = item.end_date.split('/');
            item.end_date = '20'+toDou(Number(ed[2]))+'-'+toDou(Number(ed[0]))+'-'+toDou(Number(ed[1]))
          }
          item.sortbdNumber = hlDateUtil.shellDate(item.begin_date)
          item.sortedNumber = hlDateUtil.shellDate(item.end_date)
        })
        this.exclParams.data = JSON.parse(JSON.stringify(arr));
        this.exclParams.data.map((item, index) => {
          if (item.sortbdNumber) {
            delete item.sortbdNumber;
            delete item.sortedNumber;
          }
          item.rent_possible_percent = item.rent_possible_percent.replace('%', '')
          item.rent_price_type = item.rent_price_type.indexOf('天') > -1 ? 'D' : 'M'
        })
        // 楼层归类
        var tempArr = [];
        arr.map(item => {
          if (!tempArr.length) {
            tempArr.push({floorName: item.floor_name, list: [item]})
          }
        })
        var floorFlag;
        arr.map(item => {
          floorFlag = false;
          tempArr.map(item1 => {
            if (item1.floorName == item.floor_name) {
              floorFlag = true;
            }
          })
          if (!floorFlag) {
            tempArr.push({floorName: item.floor_name, list: [item]})
          }
        })
        // 根据楼层归类单元
        var unitFlag;
        arr.map(item => {
          tempArr.map(item1 => {
            unitFlag = false;
            item1.list.map(item2 => {
              if (item1.floorName == item.floor_name) {
                unitFlag = true;
              }
            })
            if (unitFlag) {
              item1.list.push(item)
            }
          })
        })
        tempArr.map(item => {
          item.list.splice(0, 1)
        })
        //什么都能排序
        tempArr.map(item => {
          item.list = item.list.sort(compareAsc("unit_name"))
        })
        //比较
        this.exclParams.postFlag = false;
        tempArr.map(item => {
          item.list.map((item1, index) => {
            if ((index+1) < item.list.length) {
              if (item.list[index].unit_name == item.list[index+1].unit_name) {
                if (item.list[index].sortedNumber >= item.list[index+1].sortbdNumber) {
                  this.exclParams.postFlag = '1';
                }
                if (item.list[index].sortbdNumber >= item.list[index+1].sortedNumber) {
                  this.exclParams.postFlag = '0';
                }
              }
            }
          })
        })
      },
      //提交表格
      submitExcl () {
        this.exclFlagShow = true;
        if (this.exclParams.postFlag == '1') return;
        hlhttp.post({
          url: 'rent/import/unit_price_forecast',
          data: {
            unitPriceForecasts: JSON.stringify(this.exclParams.data)
          },
          success: () => {
            this.exclParams.postFlag = '2';
            setTimeout(() => {
              this.searchUnit()
              this.hideYuceAdd()
              this.exclFlag = false;
            }, 500);
          },
          error: () => {
            this.exclParams.postFlag = '1';
          }
        })
      }
    },
    mounted () {
      this.getProject()
      this.getFormats()
      this.yuceDate()
      this.scrollBottom()
      this.exclTab()
      hlSelectUi()
      document.addEventListener('click', (e) => {
        if (!this.$el.contains(e.target)) {
          this.showPositon = false;
          this.typeNumber = '';
          this.position = {left: 0, top:0, zIndex: '-1'}
        }
      })
    }
  })
} ())
